import { Component, inject, OnInit } from '@angular/core';
import { DelonFormModule, SFSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-auth2-scope-edit',
  templateUrl: './scope-edit.component.html',
  imports: [NzSpinModule, DelonFormModule, NzButtonModule]
})
export class ScopeEditComponent implements OnInit {
  record: NzSafeAny = {};
  schema: SFSchema = { properties: {} };
  ui: SFUISchema = {
    '*': {
      spanLabel: 10,
      spanControl: 14,
      grid: { span: 12 }
    }
  };

  protected readonly http = inject(_HttpClient);
  private readonly modal = inject(NzModalRef);
  private readonly msgSrv = inject(NzMessageService);

  ngOnInit(): void {
    this.initSchema();
  }

  // 初始化表单，在获取完部门树数据之后再初始化
  initSchema() {
    this.schema = {
      properties: {
        name: {
          type: 'string',
          title: '名称',
          readOnly: this.record.id && this.record.id.length > 0
        },
        description: {
          type: 'string',
          title: '描述'
        }
      },
      required: ['name', 'description']
    };
  }

  save(value: NzSafeAny) {
    console.log(value);
    if (this.record.id) {
      let data = { id: this.record.id, description: value.description };
      this.http.put(Api.BaseScopeApi, data).subscribe((res: NzSafeAny) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('修改成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('修改失败，未知错误');
        }
      });
    } else {
      this.http.post(Api.BaseScopeApi, value).subscribe((res: NzSafeAny) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('保存成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('保存失败，未知错误');
        }
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
